package io.renren.modules.yckj.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.service.impl.CrudServiceImpl;
import io.renren.modules.yckj.dao.CouponsLogsDao;
import io.renren.modules.yckj.dto.CouponsLogsDTO;
import io.renren.modules.yckj.entity.CouponsEntity;
import io.renren.modules.yckj.entity.CouponsLogsEntity;
import io.renren.modules.yckj.service.CouponsLogsService;
import io.renren.modules.yckj.service.CouponsService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Map;

/**
 * 优惠券日志
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0 2025-04-16
 */
@Service
@AllArgsConstructor
public class CouponsLogsServiceImpl extends CrudServiceImpl<CouponsLogsDao, CouponsLogsEntity, CouponsLogsDTO> implements CouponsLogsService {

    private final CouponsService couponsService;

    @Override
    public QueryWrapper<CouponsLogsEntity> getWrapper(Map<String, Object> params) {
        String id = (String) params.get("id");
        Object userId = params.get("userId");
        Object couponsId = params.get("couponsId");
        Object status = params.get("status");
        Object available = params.get("available");
        Object username = params.get("username");

        QueryWrapper<CouponsLogsEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StrUtil.isNotBlank(id), "id", id);
        wrapper.eq(ObjectUtil.isAllNotEmpty(userId), "user_id", userId);
        wrapper.eq(ObjectUtil.isAllNotEmpty(status), "status", status);
        wrapper.eq(ObjectUtil.isAllNotEmpty(couponsId), "coupons_id", couponsId);
        wrapper.like(ObjectUtil.isAllNotEmpty(username), "username", username);
        if (available != null) {
            if ((boolean) available) {
                wrapper.ge("deadline_time", new Date());
            } else {
                wrapper.le("deadline_time", new Date());
            }
        }

        return wrapper;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean receive(CouponsEntity couponsEntity, CouponsLogsDTO couponsLogsDTO) throws Exception {
        boolean b = this.save(couponsLogsDTO);
        if (!b)
            throw new Exception("优惠券领取失败！");
        b = couponsService.updateById(couponsEntity);
        if (!b)
            throw new Exception("优惠券数量更新失败！");
        return b;
    }
}